﻿@using KPIS.GERP.Models.ICM
@model KPIS.GERP.Models.ICM.Asset

@{
    ViewBag.Title = "รายละเอียดการจำหน่าย";

    var service = new KPIS.GERP.WEB.GIMS.DisposeService.DisposeServiceClient();

    int DisposeId = ViewBag.DisposeId;

    var db = new GERPContext();
    var resTypes = db.MasResourceTypes.ToList();
    var masunits = db.MasUnits.ToList();
    var modelDispose = service.SelectDispose(new Dispose { DisposeId = DisposeId, RecordStatus = "!" + KPIS.GERP.Models.SYS.RecordStatus.DeletedStatus }
    , new[] { "MasResourceType", "JobSite", "Warehouse", "DisposeType", "Employee" }
    ).FirstOrDefault();

    // ถ้ายังไม่มีการอนุมัติก็จะแสดงตารางให้เลือกพัสดุ  แต่ถ้ามีการอนุมัติแล้วก็จะซ่อนตารางเพื่อป้องกันไม่ให้เลือกพัสดุอีก
    var Expresstion = modelDispose.DisposeStatus != KPIS.GERP.Models.SYS.RecordStatus.ApprovedStatus && modelDispose.DisposeStatus != KPIS.GERP.Models.SYS.RecordStatus.ProcessStatus;


    // ตรวจสอบสถานที่ต้นทางว่ามาจากคลัง หรือมาจากหน่วยงาน หรือมาจากสถานที่อื่น
    bool checkFromWh = false;
    bool checkFromJobsite = false;
    bool checkFromPlace = false;

    if (modelDispose.FromIcmWhId != null)
    {
        checkFromWh = true;
    }
    else if (modelDispose.FromJobsiteId != null)
    {
        checkFromJobsite = true;
    }
    else if (modelDispose.FromOtherPlace != null)
    {
        checkFromPlace = true;
    }


    // ตรวจสอบสถานที่ปลายทางว่าไปหน่วยงานอื่น หรือไปสถานที่อื่น
    bool checkToOtherJobsite = false;
    bool checkToOtherPlace = false;

    if (modelDispose.ToOtherSite != null)
    {
        checkToOtherJobsite = true;
    }
    else if (modelDispose.ToOtherPlace != null)
    {
        checkToOtherPlace = true;
    }
}

<div class="row-fluid">
    @Html.ButtonViewAll()
</div>
<br />

<div class="widget-box ">
    <div class="widget-header header-color-blue2">
        <h4 class="lighter smaller">รายละเอียดการจำหน่าย</h4>
    </div>
    <div class="widget-body">
        <div class="widget-body-inner">
            <div class="widget-main">

                <div class="form-horizontal">

                    <div class="control-group">
                        <div class="control-label">
                            รหัสรายการ :
                        </div>
                        <div class="controls">
                            DS@(modelDispose.DisposeId.ToString("00000"))
                        </div>
                    </div>
                    <div class="control-group">
                        <div class="control-label">
                            วันที่ทำรายการ :
                        </div>
                        <div class="controls">
                            @(modelDispose.DisposeDate.HasValue ? 
                            modelDispose.DisposeDate.Value.ToString("dd/MM/yyyy",new System.Globalization.CultureInfo("th-TH")):"")
                        </div>
                    </div>

                    <div class="control-group">
                        <div class="control-label ">
                            เรื่อง :
                        </div>
                        <div class="controls">
                            @modelDispose.DisposeDesc
                        </div>
                    </div>

                    <div class="control-group">
                        <div class="control-label ">
                            ประเภทพัสดุ :
                        </div>
                        <div class="controls">
                            @modelDispose.MasResourceType.Name
                        </div>
                    </div>

                    <div class="control-group">
                        <div class="control-label ">
                            ประเภทรายการ :
                        </div>
                        <div class="controls">
                            @modelDispose.DisposeType.LookUpName
                        </div>
                    </div>

                    <div class="control-group">
                        <div class="control-label ">
                            วิธีการจำหน่าย :
                        </div>

                        <div class="controls">
                            <span class="lbl"><b>สถานที่ต้นทาง</b></span>&nbsp&nbsp&nbsp&nbsp&nbsp
                            @Html.RadioButton("radioF", "FWh", checkFromWh, new { @disabled = "disabled" })<span class="lbl"><b>จากคลัง</b></span>
                            <span id="FromWarehouse">
                                <b>: </b>
                                @(modelDispose.Warehouse == null ? "-":modelDispose.Warehouse.Name)
                            </span>&nbsp&nbsp&nbsp&nbsp&nbsp

                            @Html.RadioButton("radioF", "FJobsite", checkFromJobsite, new { @disabled = "disabled" })<span class="lbl"><b>จากหน่วยงาน</b></span>
                            <span id="FromJobsite">
                                <b>: </b>
                                @(modelDispose.Jobsite != null ? modelDispose.Jobsite.Name: "-")
                            </span>&nbsp&nbsp&nbsp&nbsp&nbsp

                            @Html.RadioButton("radioF", "FOtherPlace", checkFromPlace, new { @disabled = "disabled" })<span class="lbl"><b>จากสถานที่อื่น</b></span>
                            <span id="FromOtherPlace"><b>: </b> 
                                @(string.IsNullOrWhiteSpace(modelDispose.FromOtherPlace) ? "-" : modelDispose.FromOtherPlace)
                            </span>
                        </div>

                        <br />

                        <div class="controls">
                            <span class="lbl"><b>สถานที่ปลายทาง</b></span>&nbsp&nbsp
                            @Html.RadioButton("radioT", "TJobsite", checkToOtherJobsite, new { @disabled = "disabled" })<span class="lbl">
                                <b>ไปหน่วยงานอื่น</b>
                                                                                            <span id="ToJobsite"><b> : </b>
                            @(string.IsNullOrWhiteSpace(modelDispose.ToOtherSite) ? "-":modelDispose.ToOtherSite)
                            </span>
                            </span>&nbsp&nbsp&nbsp&nbsp&nbsp
                            @Html.RadioButton("radioT", "TOtherPlace", checkToOtherPlace, new { @disabled = "disabled" })<span class="lbl">
                                <b>ไปสถานที่อื่น</b>
                                                                                             <span id="ToOtherPlace"><b> : </b>
                             @(string.IsNullOrWhiteSpace(modelDispose.ToOtherPlace) ? "-" : modelDispose.ToOtherPlace)
                            </span>
                            </span>
                        </div>

                    </div>

                    <div class="control-group">
                        <div class="control-label ">
                            หมายเหตุ :
                        </div>
                        <div class="controls">
                            @Html.Raw(string.IsNullOrWhiteSpace(modelDispose.Remark)?"-":modelDispose.Remark.Replace("\n", "<br/>\n"))
                        </div>
                    </div>
                </div>
            
            </div>
        </div>
    </div>
</div>

<br/>
<div class="widget-box">
	<div class="widget-header header-color-blue2">
        <div class="widget-toolbar">
            <a href="#" data-action="collapse" style="color:#fff;font-size:large;" ><i class="icon-chevron-up"></i>  
            รายละเอียดการจำหน่าย</a>
		</div>
    </div>
    <div class="widget-body">
        <div class="widget-main">
            @* ตารางแสดงรายการพัสดุที่เลือกแล้ว *@
            <div class="row-fluid">
                <div class="row-fluid">
                    <div class="table-header span12">
                        <div class="span10">
                            รายการที่เลือก
                        </div>
                        @Html.Partial("_ExportButton")
                    </div>
                </div>
                <table id="table1" class="table table-striped table-bordered table-hover" aria-describedby="table_info">
                    <thead>
                        <tr>
                            <th>หมายเลข/รหัส</th>
                            <th>ชื่อรายการ</th>
                            <th>รายละเอียด</th>
                            <th>จำนวน</th>
                            <th>หน่วย</th>
                            <th>สถานะ</th>
                            <th></th>
                        </tr>
                    </thead>

                    <tbody>
                        @* กรณีเป็นวัสดุ *@
                        @if (modelDispose.ResTypeId == 1)
                        {
                            var modelDisposeOfficeSuppliesLotHistory = service.SelectDisposeOfficeSupplylotHistory(new DisposeOfficeSupplylotHistory
                            {
                                RecordStatus = "!" + KPIS.GERP.Models.SYS.RecordStatus.DeletedStatus,
                                DisposeId = DisposeId
                            }, new[] { "Dispose", "OfficeSuppliesLot", "OfficeSuppliesLot.MasResourceItem", "OfficeSuppliesLot.MasUnit" }).ToList();

                            foreach (var m in modelDisposeOfficeSuppliesLotHistory ?? null)
                            {
                                <tr>
                                    <td>ล็อตที่ : @m.OfficeSuppliesLot.LotNo</td>
                                    <td>@m.OfficeSuppliesLot.MasResourceItem.Name</td>
                                    <td>@m.OfficeSuppliesLot.Description</td>
                                    <td>@m.OfficeSuppliesLot.Quantity</td>
                                    <td>@m.OfficeSuppliesLot.MasUnit.Name</td>
                                    <td style="text-align: center; font-weight: bold">
                                        <span class="
                                              @{ switch (m.RecordStatus) { case "U": @: text-info
                                                         break; case "A": @: text-success
                                                         break; case "W": @: text-warning
                                                         break; case "P": @: muted
                                                         break; case "J": @: red
                                                         break; default: break; } } ">
                                            @KPIS.GERP.Models.SYS.RecordStatus.RecordStatusName(m.RecordStatus)

                                        </span>
                                    </td>
                                    <td>
                                        @if (Expresstion)
                                        {
                                            @Html.ActionLink("  ยกเลิก", "UnSelect", new
                                            {
                                                id = m.DisposeOfficeSupplylotHisId,
                                                ResTypeId = modelDispose.ResTypeId, 
                                                ResourceType = modelDispose.MasResourceType.Name,
                                                DisposeId = DisposeId
                                            }
                                                , new { @class = "btn btn-danger btn-mini icon-trash", role = "button" })
                                        }
                                    </td>
                                </tr>
                            }
                        }
                        @* กรณีเป็นครุภัณฑ์ *@
                        else
                        {
                            var modelMovementHistory = service.SelectMovementHistory(new MovementHistory
                            {
                                RecordStatus = "!" + KPIS.GERP.Models.SYS.RecordStatus.DeletedStatus,
                                MovementType = "Dispose",
                                MoveRefNo = DisposeId
                            }, new[] { "Asset", "Asset.MasUnit" }).ToList();
                            foreach (var m in modelMovementHistory == null ? null : modelMovementHistory)
                            {
                                <tr>
                                    <td>@m.Asset.SerialNumber </td>
                                    <td>@m.Asset.AssetName  รหัส : @m.Asset.AssetCode </td>
                                    <td>@m.Asset.Description</td>
                                    <td>@m.Asset.Quantity</td>
                                    <td>@m.Asset.MasUnit.Name</td>
                                    <td style="text-align: center; font-weight: bold">
                                        <span class="
                                              @{ switch (m.RecordStatus) { case "U": @: text-info
                                                                                                                         break; case "A": @: text-success
                                                                                                                         break; case "W": @: text-warning
                                                                                                                         break; case "P": @: muted
                                                                                                                         break; case "J": @: red
                                                                                                                         break; default: break; } } ">
                                            @KPIS.GERP.Models.SYS.RecordStatus.RecordStatusName(m.RecordStatus)

                                        </span>
                                    </td>
                                    <td>
                                        @if (Expresstion)
                                        {
                                            @Html.ActionLink("  ยกเลิก", "UnSelect", new { id = m.MoveHistId, ResourceType = modelDispose.MasResourceType.Name, DisposeId = DisposeId }
                                    , new { @class = "btn btn-danger btn-mini icon-trash", role = "button" })
                                        }
                                    </td>
                                </tr>
                            }
                        }
                    </tbody>

                </table>
            </div>



            @* ตารางเลือกพัสดุที่ต้องการจำหน่าย *@
            @using (Html.BeginForm("SelectAll", "Dispose", FormMethod.Post, new { id = "form" }))
            {
                @Html.Hidden("hdDisposeId", DisposeId)

                if (Expresstion)
                {
                    <div class="row-fluid">
                        <p id="message"></p>

                        <div class="block-button-menu-above">
                            <button class="btn btn-small btn-success btn-small" type="submit">
                                <i class="icon-check bigger-120"></i>ตกลงเลือกรายการพัสดุ
                            </button>
                        </div>

                        <div class="alert-error">@Html.ValidationSummary()</div>

                        <div class="row-fluid">
                            <div class="table-header span12">
                                <div class="span10">
                                    เลือกรายการที่ต้องการจำหน่าย
                                </div>
                                @Html.Partial("_ExportButton")
                            </div>
                        </div>

                        <table id="table" class="table table-striped table-bordered table-hover" aria-describedby="table_info">
                            <thead>
                                <tr>
                                    <th class="center" style="width: 50px;">
                                        <!-- Check box delete multiple records column-->
                                        <label>
                                            <input type="checkbox" />
                                            <span class="lbl"></span>
                                        </label>
                                    </th>
                                    <th style="width:100px">หมายเลข/รหัส</th>
                                    <th style="width:220px; ">ชื่อรายการ</th>
                                    <th style=" ">ยี่ห้อ/ขนาด</th>
                                    <th style="width:90px">จำนวน</th>
                                    <th style="width:90px">หน่วยนับ</th>
                                    <td style="width:90px">ประเภทพัสดุ</td>
                                    <td style="width:100px">#</td>
                                </tr>
                            </thead>

                            <tbody>
@* กรณีเป็นวัสดุ *@
@if (modelDispose.ResTypeId == 1)
{  
    // เลือกรายการวัสดุ ตามใบตรวจนับ(IcmInventoryStockTakingItems)
    IQueryable<OfficeSuppliesLot> QueryOfficesupplieslot = (from a in db.OfficeSuppliesLots.Include("MasResourceItem.MasResourceSubGroup.MasResourceGroup.MasResourceType").Include("MasUnit")
        /*join b in db.InventoryStockTakingItems on a.ResItemId equals b.ResItemId
                                                            join c in db.InventoryStockTakings on b.StockTakingId equals c.StockTakingId
                                                            */
        where a.RecordStatus != "D"

        /*
                                                            && b.RecordStatus != "D"
                                                            && c.RecordStatus == "A"
                                                            && c.ResourceTypeId == 1 */
        select a);

    var doh = db.DisposeOfficeSupplylotHistorys.Where(o => o.RecordStatus != "D").Select(o=>o.OfficeSuppliesLotId).ToList();
    var modelOfficeSuppliesLot = QueryOfficesupplieslot.Where(o => !doh.Contains(o.OfficeSuppliesLotId)).ToList();

    // เลือกรายการวัสดุ ในตาราง IcmDisposeOfficeSupplylotHistory
    /* var MovementHistory = (from a in db.DisposeOfficeSupplylotHistorys
                           join b in db.OfficeSuppliesLots on a.OfficeSuppliesLotId equals b.OfficeSuppliesLotId
                            where a.RecordStatus != "D"
                            && b.RecordStatus != "D"
                            select b).ToList();*/ 

    // เลือกรายการวัสดุ โดยตัดวัสดุที่อยุ่ในตาราง IcmDisposeOfficeSupplylotHistory ออก
     //var modelOfficeSuppliesLot = ListOfficesupplieslot.Except(MovementHistory).ToList();
     
    // var modelOfficeSuppliesLot = service.SelectOfficeSuppliesLot(modelDispose.ResTypeId, modelDispose.FromIcmWhId, new[] {"MasResourceItem", "MasUnit"}).ToList();

    foreach (var m in modelOfficeSuppliesLot  )
    {
        <tr>
            <td class="center">
                <!-- Check box all for delete multiple records -->
                <label>
                    @*<input type="checkbox" name="selectIds" />*@
                    <input type="checkbox" name="selectIds" value="@m.OfficeSuppliesLotId" />
                    <span class="lbl"></span>
                </label>
            </td>
            <td>@m.MasResourceItem.Code</td>
            <td>@m.MasResourceItem.Name  ล็อตที่ : @m.LotNo</td>
            <td>@m.Description</td>
            <td>@m.Quantity</td>
            <td>@m.MasUnit.Name</td>
            <td>@m.MasResourceItem.MasResourceSubGroup.MasResourceGroup.MasResourceType.Name</td>
            <td>@Html.ActionLink("  เลือก", "Select", new {id = m.OfficeSuppliesLotId, DisposeId = ViewBag.DisposeId}, new {@class = "btn btn-success btn-mini icon-check", role = "button"})</td>
        </tr>
    }
}
                                @* กรณีเป็นครุภัณฑ์ *@
                                else
                                {
                                    var assets = db.Assets.Include(o => o.MasUnit).Include(o => o.MasResourceType)
                                    .Where(o => o.RecordStatus != "D").ToList();
                                    
                                var assetsDisposed = db.MovementHistorys
                                .Where(o => o.RecordStatus != "D" && o.MovementType == "Dispose").ToList();

                                var assetNotDisposed = assets.Where(o => !assetsDisposed.Any(j => j.AssetId == o.AssetId)).ToList();
                                    
                                var isti = db.InventoryStockTakingItems.Where(o => o.RecordStatus != "D").ToList();

                                var ist = db.InventoryStockTakings.Where(o => o.RecordStatus != "D").ToList();


                                var result1 = assetNotDisposed.Select(o => new
{
    Asset = o,
    InventoryStockTakingItems = isti.FirstOrDefault(j => j.ResItemId == o.ResItemId),

    InventoryStockTakings = isti.FirstOrDefault(j => j.ResItemId == o.ResItemId) != null ?
                                ist.FirstOrDefault(k => k.StockTakingId == isti.FirstOrDefault(j => j.ResItemId == o.ResItemId).StockTakingId) : null
});
@*var result1 = (from a in context.Assets.Include(o => o.MasUnit).Include(o => o.MasResourceType)
    join b in context.InventoryStockTakingItems.DefaultIfEmpty() on a.ResItemId equals b.ResItemId
    join c in context.InventoryStockTakings.DefaultIfEmpty() on b.StockTakingId equals c.StockTakingId
where a.RecordStatus != "D" // && a.AssetTypeId == modelDispose.ResTypeId
 && b.RecordStatus != "D"
    && c.RecordStatus == "A"
    && c.ResourceTypeId == modelDispose.ResTypeId 
select new{Asset = a , InventoryStockTakingItems = b, InventoryStockTakings=c});*@
// var modelAsset = service.SelectAsset(modelDispose.ResTypeId, modelDispose.FromIcmWhId, modelDispose.FromJobsiteId, new[] { "MasUnit" }).ToList();
    foreach (var data in result1)
    {
        var m = data.Asset;
        var resType = resTypes.FirstOrDefault(o=>o.ResTypeId == m.AssetTypeId);
        var masUnit = masunits.FirstOrDefault(o=>o.UnitId == m.UnitId);
        <tr>
            <td class="center">
            <!-- Check box all for delete multiple records -->
            <label>
            @*<input type="checkbox" name="selectIds" />*@
            <input type="checkbox" name="selectIds" value="@m.AssetId" />
            <span class="lbl"></span>
            </label>
            </td>
            <td>@(data.Asset.SerialNumber)</td>
            <td>@(data.Asset.AssetName) : @m.AssetCode</td>
            <td>@m.Description</td>
            <td>@m.Quantity</td>
            <td>@(masUnit != null ? masUnit.Name : "")</td>
            <td>@(resType != null ? resType.Name : "")</td>
            <td>@Html.ActionLink("  เลือก", "Select", 
            new {id = m.AssetId, DisposeId = ViewBag.DisposeId}, 
            new {@class = "btn btn-success btn-mini icon-check", role = "button"})</td>
        </tr>
    }
}
                            </tbody>

                        </table>
                    </div>
                }
                else
                {
                    
                }
            
            }
            <br />

        </div>
    </div>
</div>



<br />
<div class="widget-box ">
	<div class="widget-header header-color-blue2">
        <div class="widget-toolbar">
            <a href="#" data-action="collapse" style="color:#fff;font-size:large;" ><i class="icon-chevron-up"></i>  คณะกรรมการ</a>
		</div>
    </div>
    <div class="widget-body">
        <div class="widget-main">
            @if (modelDispose.CommitteeGroupId == null)
            { 
                var cgi = new CommitteeGroup {RecordStatus = "U"};
                  
                db.CommitteeGroups.Add(cgi);
                db.SaveChanges();

                var disposTemp = db.Disposes.Find(modelDispose.DisposeId);
                disposTemp.CommitteeGroupId = cgi.CommitteeGroupId;
                db.Entry(disposTemp).State = EntityState.Modified;
                db.SaveChanges();

                modelDispose = db.Disposes.Find(modelDispose.DisposeId);
            }
            @*<iframe id="iframe2" src="@Url.Action("IndexDisposeCommittee", "Dispose", new { DisposeId = DisposeId })" frameborder="0" style="width:100%; min-height:500px"; ></iframe>*@
            <iframe id="iframe2" src="@Url.Action("Index", "Committee")?CommitteeGroupId=@(modelDispose.CommitteeGroupId)&EmptyLayout=@(ViewBag.EmptyLayout == true  ? "true" : "false")" frameborder="0" style="width:100%;"></iframe>
        </div>
    </div>
</div>



@section scripts {
	<script type="text/javascript">

	    $(function () {
	        var lastHeight = 0, curHeight = 0, $frame = $('iframe');
	        setInterval(function () {
	            curHeight = $frame.contents().find('body').height() + 40;
	            if (curHeight != lastHeight) {
	                $frame.css('height', (lastHeight = curHeight) + 'px');
	            }
	        }, 500);
	    });

	    $(function () {
	        var oTable1 = $('#table').dataTable({
	            "aoColumns": [
                    { "bSortable": false },
                    null, null, null, null, null, null, 
                    { "bSortable": false }
	            ]
	        });

	        $('table th input:checkbox').on('click', function () {
	            var that = this;
	            $(this).closest('table').find('tr > td:first-child input:checkbox')
				.each(function () {
				    this.checked = that.checked;
				    $(this).closest('tr').toggleClass('selected');
				});

	        });

	        $('[data-rel=tooltip]').tooltip();
	    })

	    $(function () {
	        var oTable1 = $('#table1').dataTable({
	            "aoColumns": [
                    { "bSortable": false },
                    null, null, null, null, null,
                    { "bSortable": false }
	            ]
	        });

	        $('table th input:checkbox').on('click', function () {
	            var that = this;
	            $(this).closest('table').find('tr > td:first-child input:checkbox')
				.each(function () {
				    this.checked = that.checked;
				    $(this).closest('tr').toggleClass('selected');
				});

	        });

	        $('[data-rel=tooltip]').tooltip();
	    })

	    $("form").submit(function () {
	        var currentForm = this;
	        var disposeId = $("#hdDisposeId").val();
	        bootbox.confirm(function (result) {
	            var _result = result;
	            if (result) {
	                $.ajax({
	                    url: '@(Url.Action("SelectAll", "Dispose"))',
			            type: "post",
			            dataType: "json",
			            data: $(currentForm).serialize(),
			            success: function (result) {
			                if (result.success) {
			                    $("#message").html(result.message);
			                    location.href = '@Url.Action("Details", "Dispose")' + "?id=" + disposeId;
			                    //location.reload();
			                }
			                else {
			                    $("#message").html(result.message);
			                }
			            }
			        });
                }
            })
            return false;
        });

	</script>

}